package com.ifinc.common.db.partition;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-28
 * Time: 18:27
 */
public class BasePartitionDao implements FactoryBean, ApplicationContextAware {

    ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public Map<String, JdbcTemplate> templateMap = new HashMap<String, JdbcTemplate>();

    @Override
    public Object getObject() throws Exception {
        Map<String, DataSource> dataSource = context.getBeansOfType(DataSource.class);
        for (Map.Entry<String, DataSource> dataSourceEntry : dataSource.entrySet()) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceEntry.getValue());
            templateMap.put(dataSourceEntry.getKey(), jdbcTemplate);
        }
        return this;
    }

    @Override
    public Class<?> getObjectType() {
        return BasePartitionDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void update(IPartitionCondition condition) {
        //获得数据库的下标
        String templateIndex = condition.getDbIndex();

        JdbcTemplate jdbcTemplate = templateMap.get(templateIndex);

        String partition_sql = condition.getPartitionSql();

        Object[] values = condition.getPartitionValues();

        jdbcTemplate.update(partition_sql, values);
    }
}
